import axios from 'axios'
import store from './store/store'
import * as types from './store/types'
import router from './router/index'

// axios 配置
axios.defaults.timeout = 20000;
//根目录
axios.defaults.baseURL = '';


// http request 拦截器
axios.interceptors.request.use(
  config => {
    if (localStorage.token) {
      config.params  = config.params||{}
      config.params.token = `${localStorage.token}`;
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  });

// http response 拦截器
// 监测是否登陆了
axios.interceptors.response.use(
  response => {
    switch (response.data.code) {
      case 401:
        // 401 清除token信息并跳转到登录页面
           store.commit(types.LOGOUT);
           router.replace({
             path: 'login',
             query: {redirect: router.currentRoute.fullPath}
          
           })
    }
    return response;
  },
  error => {
    throw error
  });

export default axios;
